﻿using HamcoWcs.Entitys.DeviceMsgQueues;
using HamcoWcs.Entitys.SubTasks;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.DeviceMsgQueues;
using HamcoWcs.Models.DeviceMsgs;
using HamcoWcs.Models.Devices;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

namespace HamcoWcs.Workers
{
    public partial class PconWorker
    {

        /// <summary>处理任务</summary>
        private void DealTask(PconPlc pconPlc)
        {
            // 获取已就绪的任务
            var subTasks = _wcsDbContext.Set<SubTask>()
                                        .Where(x => x.TaskStatus == EnumSubTaskStatus.Ready.ToString())
                                        .Where(x => x.PlcName == pconPlc.PlcName)
                                        .Include(x => x.MainTask)
                                        .Where(x => x.MainTask.TaskStatus == EnumMainTaskStatus.Ready.ToString()
                                                 || x.MainTask.TaskStatus == EnumMainTaskStatus.OnProgress.ToString())
                                        .ToList();



            if (!subTasks.Any()) return;

            foreach (var subTask in subTasks)
            {
                //if (err)
                //{

                //}


                var fromNode = _pathService.GetWmsNode(subTask.FromLoc);
                //if (!fromNode.IsRunning) continue;
                var toNode = _pathService.GetWmsNode(subTask.ToLoc);
                //if (!toNode.IsRunning) continue;

                if (string.IsNullOrEmpty(fromNode.InName))
                {
                    continue;
                }
                int fromLoc = int.Parse(fromNode.InName);
                var fromPcon = _asrs.ConveyorDic[pconPlc.PlcName].Pcons[fromLoc];
                if (fromPcon.IsGoods == 0) continue;
                if (fromPcon.UnitId != subTask.UnitId) continue;

                // 如果是提升机或者RGV则下发下一段位置的目的地
                SubTask nextSubTask = null;
                if (GlobalValue.SpecialNodes.Contains(toNode.NodeName))
                {
                    nextSubTask = GetNextSubTask(subTask);
                    toNode = _pathService.GetWmsNode(nextSubTask.ToLoc);
                    //if (!toNode.IsRunning) continue;
                }
                #region TODO
                //// 成品入库检测提升机是否占用 （目前不需要做）
                //if (GlobalValue.ProductInNodes.Contains(subTask.MainTask.SrcMachine) && subTask.ToLoc.Equals("CJMIFC00"))
                //{
                //    var nextTask = GetNextSubTask(subTask);
                //    PconDto pcon = null;
                //    pcon = _pconBaseService.GetPcon("CJMIFC00", "01");
                //    if (pcon == null || pcon.IsGoods == 1 || !CheckPconMode(pcon.PconMode))
                //    {
                //        _logger.AddSystemErrorLog($"PconWorker->DealTask:任务{subTask.MainTask.TaskId}下发任务异常，CJMIFC00提升机设备异常或者卡货");
                //        continue;
                //    }
                //    if (nextTask.ToLoc.Contains("CJVCV600"))
                //    {
                //        pcon = _pconBaseService.GetPcon(nextTask.ToLoc, "06");
                //    }
                //    else if (nextTask.ToLoc.Contains("CJVCV800"))
                //    {
                //        pcon = _pconBaseService.GetPcon(nextTask.ToLoc, "07");
                //    }
                //    if (pcon == null || pcon.IsGoods == 1 || !CheckPconMode(pcon.PconMode))
                //    {
                //        _logger.AddSystemErrorLog($"PconWorker->DealTask:任务{subTask.MainTask.TaskId}下发任务异常，{pcon.MachineName}设备异常或者卡货");
                //        continue;
                //    }
                //}
                #endregion
                if (string.IsNullOrEmpty(toNode.InName))
                {
                    _logger.AddSystemErrorLog($"PconWorker->DealTask:任务{subTask.MainTask.TaskId}下发任务异常，未获取到正确的目的地");
                    continue;
                }

                ushort toLoc = ushort.Parse(toNode.InName);


                var msg = PconSendMsg.CreateDestMsg((ushort)fromLoc, toLoc, subTask.UnitId);
                var deviceMsgQueueDto = new DeviceMsgQueueDto(fromPcon, msg);
                var deviceMsgQueue = _mapper.Map<DeviceMsgQueue>(deviceMsgQueueDto);

                //// todo写日志
                //long id = subTask.Id;
                //if (nextSubTask != null)
                //{
                //    subTask.TaskStatus = EnumSubTaskStatus.Finished.ToString();
                //    id = nextSubTask.Id;
                //}

                _wcsDbContext.DeviceMsgQueues.Add(deviceMsgQueue);
                _baseTaskService.UpdateSubTaskStatus(subTask.Id, EnumSubTaskStatus.OnProgress);
            }
        }

        private bool CheckPconMode(int mode)
        {
            if (mode != 1 || mode != 6 || mode != 7)
            {
                return false;
            }
            return true;
        }
        private SubTask GetNextSubTask(SubTask subTask)
        {
            var mainTask = _wcsDbContext.MainTasks
                .Where(x => x.Id == subTask.MainTask.Id)
                .Include(x => x.SubTasks)
                .FirstOrDefault();

            return mainTask.SubTasks.FirstOrDefault(x => x.TaskSeq == subTask.TaskSeq + 1);

            //return mainTask.SubTasks[subTask.TaskSeq];
        }
    }
}
